

    function threeSum(nums, target) {
        let resultList = [];
        for (let i = 0; i < nums.length; i++) {
            let map = Map();
            let d1 = target - nums[i];
            //寻找两数之和等于d1的组合
            for (let j = i+1; j < nums.length; j++) {
                let d2 = d1 - nums[j];
                if (map.has(d2)) {
                    resultList.push([nums[i], d2, nums[j]]);
                }
                map.put(nums[j], j);
            }
        }
        return resultList;
    }

    function threeSumv2(nums, target) {
        //先对数组排序
        nums.sort((a,b)=>{
            if (a>b) {
                return 1;
            }else if (a<b) {
                return -1;
            }else {
                return 0;
            }
        })
        let resultList = [];
        //大循环
        for (let i = 0; i < nums.length; i++) {
            let d = target - nums[i];
            // j和k双指针循环定位，j在左端，k在右端
            for (let j=i+1,k=nums.length-1; j<nums.length; j++) {
                // k指针向左移动
                while (j<k && (nums[j]+nums[k])>d) {
                    k--;
                }
                //双指针重合，跳出本次循环
                if (j == k) {
                    break;
                }
                if (nums[j] + nums[k] == d) {
                    let list = [nums[i], nums[j], nums[k]];
                    resultList.push(list);
                }
            }
        }
        return resultList;
    }

   


    let nums = [5,12,6,3,9,2,1,7];
    let resultList = threeSumv2(nums, 12);
    console.log(resultList);